<template>
  <tl-sub-page :render="render" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <div class="mpm-project-container">
      <div style="width:0px;overflow:hidden;height:0px;"><input type="text" /></div>
      <div class="mpm-project-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_project.png" class="logo" style="width: 55px;height: 55px" />
          <div class="content" :title="model.projectname">
            <p>
              <b v-if="model.id">{{ model.projectname + '-' }}</b>
              <b>项目立项</b>
            </p>
            <p class="light">
              <span>项目经理：{{ model.projectmanager ? model.projectmanager + '【' + model.projectmanagercode + '】' : user.name + '【' + user.code + '】' }}</span>
              <span>创建时间：{{ model.createon ? formatDate(model.createon) : formatDate(new Date()) }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar">
          <el-button type="danger" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="mpm-project-nav" :style="{ height: mainHeight + 'px', top: '60px' }">
        <ul class="nav-list">
          <template v-for="item in navList">
            <li :key="item.code" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 150px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <div class="mpm-project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="mpm-project-main-container" id="mpmMainContainer">
          <tl-project-info ref="projectInfoRef" :isProcessApproval="this.isProcessApproval" :isApprovalCEO="isApprovalCEO" :approvalExtraParam="approvalExtraParam" :extraParam="extraParam" @loaded="loaded"></tl-project-info>
        </el-scrollbar>
      </div>
    </div>
    <tl-approval-history ref="history" sourceType="MpmProject" :sourceId="model.id" />
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit_edit } from '../../../mixins/mixin_approval_edit'
import { mixin_page_fields_custom } from '@/views/gpm/gpmProjectInfo/mixin/mixin_page_fields_custom.js'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
import tlProjectInfo from './component/projectConponent.vue'
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit_edit],
  components: { tlProjectInfo },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error('请输入内容'))
      } else {
        return callback()
      }
    }
    return {
      bidrequired: true,
      moduleTitle: '项目立项',
      urlPrefix: '/sd/project/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/mpm/project/queryOrgByDeptId',
        list: '/cbo/approvalNodeIns/list',
        changeList: '/mpm/project/changeList',
        add: '/sd/project/doSave',
        edit: '/sd/project/doSave',
        queryCeoInfo: '/sd/project/queryCeo',
        projectApproval: '/sd/project/projectApproval',
        queryProjectApprovalId: '/sd/wfForm/queryProjectApprovalId'
      },
      tabName: 'projectbasicinfo',
      sorterInfo: {
        // 排序参数
        sidx: 'id',
        sord: 'desc'
      },
      midChangePoint: true,
      datas: [],
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      rowKeyStr: 'CODE',
      loading: false,
      visible: false,
      listMode: true,
      externalMQueryParamForPool: {},
      externalDQueryParamForPool: {},
      // 项目立项规则校验重写
      addRules: {
        // 基本信息TAB表单校验
        rulesForInfo: [{ validator: validateForTab, tabname: 'projectbasicinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        // 案例概述TAB表单验证
        rulesForCustomeryInfo: [{ validator: validateForTab, tabname: 'projectcustomerinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        rulesForCompetitorInfo: [{ validator: validateForTab, tabname: 'projectcompetitorinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }]
      },
      // 项目级别默认编码值，根据选择的机会点确定
      tempprojectlevel: '',
      // 项目级别默认显示值，根据选择的机会点确定
      tempdispprojectlevel: '',
      // CEO信息
      tempdecisionusercode: '',
      tempdecisionusername: '',
      mainHeight: 1000,
      mainScrollElement: null,
      navList: [{ name: '立项信息', on: true, code: 'basic' }, { name: '项目背景', on: false, code: 'background' }, { name: '申请信息', on: false, code: 'apply' }, { name: '审批历史', on: false, code: 'history' }],
      // 审批节点配置的额外参数
      extraParam: '',
      // 判断是否是审批组件调用
      fromApproval: '',
      oldprojectlevel: '',
      // 项目等级，例：网级、省级等
      maxLevel: -1,
      // 微前端调用该组件时传递的来源类型
      sourceType: '',
      // 是否已自动选择机会点标志位
      autoSelected: 0,
      // 微前端调用时传递的机会点编号
      chancecode: '',
      contractchanged: false,
      approvalkeylist: ['isApprovalCEO', 'approvalExtraParam', 'extraParam'],
      isApprovalCEO: '',
      approvalExtraParam: '',
      isProcessApproval: ''
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    }
  },
  watch: {
  },
  computed: {
  },
  methods: {
    loaded(modeldata) {
      this.model = modeldata
      this.loading = false
    },
    beforeApproval(resolve, reject) {
      // 走流程管理项目
      if (this.isProcessApproval === '1') {
         if (!this.$refs.projectInfoRef.doSubmitEdit()) {
           reject()
         }
      }
      let that = this
      if (that.uiOperateState === 3 || this.isApprovalCEO !== '' || 'LIN' === this.approvalExtraParam || 'LINInvite' === this.approvalExtraParam) {
        let p = new Promise(that.$refs.projectInfoRef.beforeApproval)
        p.then(function (result) {
          resolve()
        }).catch((err) => {
          if (typeof err === 'undefined' || err === null) {
          } else if (err.message) {
            that.$tap.alert(err.message)
          } else {
            that.$tap.alert(err)
          }
          reject()
        })
      } else {
        resolve()
      }
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.contractchanged = false
      this.resizeHandler()
      let that = this
      that.$nextTick(() => {
        let approvalparam = that.approvalNodeModel.approvalparam
        if (approvalparam !== null) {
          let approvalparamjson = JSON.parse(approvalparam)
          that.approvalkeylist.forEach((item) => {
            if (approvalparamjson.hasOwnProperty(item)) {
              that[item] = approvalparamjson[item]
            } else {
              that[item] = ''
            }
          })
        }
        let param = { id: that.id }
        getAction(that.url.queryProjectApprovalId, param).then((res) => {
          if (res.success) {
            that.model = res.result.projectinfo
            that.$refs.projectInfoRef.id = that.model.id
            that.$refs.projectInfoRef.uiOperateState = that.uiOperateState
            if (that.uiOperateState === 3) {
              that.$refs.projectInfoRef.disableEditSubmit = false
            } else {
              that.$refs.projectInfoRef.disableEditSubmit = true
            }
            that.$refs.projectInfoRef.open()
          } else {
            that.$tap.alert(res.message, 'warining')
          }
        })
        that.mainScrollElement = this.$el.querySelector('#mpmMainContainer .el-scrollbar__wrap')
        that.onMainScroll()
      })
    },
    close() {
      this.tempprojectlevel = ''
      this.tempdispprojectlevel = ''
      this.maxLevel = -1
    },
    /** 打开调整项目级别的弹框 **/
    openChangeLevelDialog() {
      this.$refs.changeLevelRef.projectlevelList = this.codeModel.projectlevelList
      this.$refs.changeLevelRef.dispprojectdefaultlevel = this.tempdispprojectlevel
      this.$set(this.$refs.changeLevelRef.model, 'projectlevel', this.model.projectlevel)
      this.$set(this.$refs.changeLevelRef.model, 'dispprojectlevel', this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel).name)
      this.$set(this.$refs.changeLevelRef.model, 'changelevelreason', this.model.changelevelreason)
      this.$refs.changeLevelRef.visible = true
    },
    /** 填写调整项目等级原因后回写数据 **/
    confirmChangeLevel(data) {
      this.$set(this.model, 'projectlevel', data.projectlevel)
      this.$set(this.model, 'changelevelreason', data.changelevelreason)
    },
    afterSubmit() {
      this.loaded()
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd')
    },
    /** 点击左侧导航，抽屉组件必有 **/
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      const scrollFun = () => {
        const currentEl = [...this.$el.getElementsByClassName('step-position')].find((item) => item.getBoundingClientRect().y >= 0)
        const code = currentEl ? currentEl.id : ''
        this.navList.forEach((m) => (m.on = m.code === code))
      }
      this.mainScrollElement.removeEventListener('scroll', scrollFun)
      this.mainScrollElement.addEventListener('scroll', scrollFun)
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    // 抽屉组件必有
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>
<style scoped>
.formLine {
  position: relative;
  margin: 0 auto;
  width: 900px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.formLineTitle {
  position: absolute;
  left: 12%;
  font-family: "kaiTi";
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
</style>
